package dao;

import entities.Country;
import wrappers.CountryWrap;
import exceptions.DatabaseException;
import java.sql.*;
import java.util.List;

/**
 *
 * @author KAV
 */
public class CountryDAO extends AbstractDAO {

    @Override
    protected PreparedStatement stringForInsert(Connection c, Object obj) throws DatabaseException {
        try {
            Country e = (Country) obj;
            PreparedStatement st = c.prepareStatement("INSERT INTO countries(title) VALUES (?)");
            st.setString(1, e.getTitle());
            return st;
        } catch (SQLException ex) {
            throw new DatabaseException(ex);
        }
    }
   
    @Override
    protected PreparedStatement stringForDeleteById(Connection c, int id) throws DatabaseException {
        try {
            PreparedStatement st = c.prepareStatement("DELETE FROM countries WHERE id=?");
            st.setInt(1, id);
            return st;
        } catch (SQLException ex) {
            throw new DatabaseException(ex);
        }
    }
    
    @Override
    protected PreparedStatement stringForUpdateById(Connection c, Object obj) throws DatabaseException {
        try {
            Country e = (Country) obj;
            PreparedStatement st = c.prepareStatement("UPDATE countries SET title=? WHERE id=?");
            st.setString(1, e.getTitle());
            st.setInt(2, e.getId());
            return st;
        } catch (SQLException ex) {
            throw new DatabaseException(ex);
        }
    }

    @Override
    protected List<Object> processForSelectAll(Connection c) throws DatabaseException {
        List<Object> list = new java.util.LinkedList<Object>();
        try {
            PreparedStatement st = c.prepareStatement("SELECT * FROM countries");
            ResultSet rs = st.executeQuery();
            while (rs.next()) {
                Country _country = new Country();
                _country.setId(rs.getInt("id"));
                _country.setTitle(rs.getString("title"));
                CountryWrap ew = new CountryWrap(_country);
                list.add((Object) ew);
            }
        } catch (SQLException ex) {
            throw new DatabaseException(ex);
        }
        return list;
    }

    @Override
    protected Object processForSelectId(Connection c, int id) throws DatabaseException {
        Object obj = new Object();
        try {
            PreparedStatement st = c.prepareStatement("SELECT * FROM countries WHERE id=?");
            st.setInt(1, id);
            ResultSet rs = st.executeQuery();
            while (rs.next()) {
                Country e = new Country();
                e.setId(rs.getInt("id"));
                e.setTitle(rs.getString("title"));
                obj = (Object) e;
                break;
            }
        } catch (SQLException ex) {
            throw new DatabaseException(ex);
        }
        return obj;
    }
}
